package com.bjesc_b2c.app.appraiset.mvp.view.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.bjesc_b2c.app.appraiset.R;
import com.bjesc_b2c.app.appraiset.RequestAndResultCode;
import com.bjesc_b2c.app.appraiset.adapter.DemandCarAdapter;
import com.bjesc_b2c.app.appraiset.base.BaseActivity;
import com.bjesc_b2c.app.appraiset.mvp.presenter.DemandCarPresenter;
import com.bjesc_b2c.app.appraiset.mvp.presenter.LikeCarPresenter;
import com.bjesc_b2c.app.appraiset.mvp.presenter.impl.DemandCarPresenterImpl;
import com.bjesc_b2c.app.appraiset.mvp.presenter.impl.LikeCarPresenterImpl;
import com.bjesc_b2c.app.appraiset.mvp.view.DemandCarView;
import com.bjesc_b2c.app.appraiset.mvp.view.LikeCarView;
import com.bjesc_b2c.app.appraiset.utils.CustomSharedPreferences;
import com.bjesc_b2c.app.appraiset.widget.popupwindow.FileterCondPop;
import com.bjesc_b2c.app.appraiset.widget.popupwindow.FilterCarPop;
import com.liaoinstan.springview.container.DefaultFooter;
import com.liaoinstan.springview.widget.SpringView;
import com.orhanobut.logger.Logger;

import java.util.ArrayList;
import java.util.List;

import app.pinggushi.bjesc.com.baserecyclerview.adapter.MultiItemTypeAdapter;
import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;
import master_bean.DemandCarBean;
import master_bean.FindCarBean;
import rxbus_base.RxBus;
import rxretrofit_base.model.KeyBean;

/**
 * Created by yidong on 2017/5/23.
 */

public class DemandCarActivity extends BaseActivity implements SpringView.OnFreshListener, MultiItemTypeAdapter.OnItemClickListener, DemandCarView, LikeCarView, FilterCarPop.FilterCallback {
    @InjectView(R.id.recycler_view)
    RecyclerView recyclerView;
    @InjectView(R.id.spring_view)
    SpringView springView;
    @InjectView(R.id.tv_title)
    TextView titleTV;
    @InjectView(R.id.tv_car_name_title)
    TextView nameTitleTv;
    @InjectView(R.id.tv_filter)
    TextView filetyerTV;
    @InjectView(R.id.view_title)
    View titleview;
    @InjectView(R.id.edit_search_name)
    EditText searchNameEdit;

    private List<DemandCarBean> listCar = new ArrayList<DemandCarBean>();
    private DemandCarPresenter presenter;
    private FindCarBean findCarBean;
    private DemandCarAdapter adapter;
    private String brandId;
    private String brandName;
    private int selectPosition;
    private int page = 1;
    private int fType = 1;
    private boolean ismore = true;
    private int carId;
    private String dispatchId;
    private FileterCondPop condPop;
    private LikeCarPresenter likePresenter;
    private int dateType;
    private boolean isLodmore = true;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_demand_car);
        ButterKnife.inject(this);
        condPop = new FileterCondPop(this, popListener);
        dateType = getIntent().getIntExtra("DATATYPE", 1);
        findCarBean = new FindCarBean();
        presenter = new DemandCarPresenterImpl(this);
        if (dateType == 1) {
            titleTV.setText("需求车源");
            presenter.getDemandCars(findCarBean);
        }
        if (dateType == 2) {
            String touid = CustomSharedPreferences.getString(this, KeyBean.TOU_ID.valueOf(), KeyBean.FILE_NAME.valueOf());
            titleTV.setText("相似车源");
            findCarBean.setTou_id(touid);
            likePresenter = new LikeCarPresenterImpl(this);
            likePresenter.getLikeCars(findCarBean);
            filetyerTV.setVisibility(View.GONE);
        }
        initViews();
    }

    private void initViews() {
        springView.setListener(this);
        springView.setHeader(new DefaultFooter(this));
        springView.setFooter(new DefaultFooter(this));
        springView.setType(SpringView.Type.FOLLOW);
        LinearLayoutManager layoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
        recyclerView.setLayoutManager(layoutManager);
        searchNameEdit.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                   page = 1;
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }

    @Override
    protected void onStart() {
        super.onStart();
    }

    @Override
    public void getLikeCars(List<DemandCarBean> datas) {
        setDates(datas);//相似车源
    }

    @Override
    public void getDemandCars(List<DemandCarBean> datas) {
        setDates(datas);//需求车源
    }

    @Override
    public void addCarSuccess() {
        setResult(22);
        finish();
    }

    private void setDates(List<DemandCarBean> datas) {
        if (datas != null && datas.size() > 0) {
            springView.setEnable(true);
            if (page == 1) {
                listCar.clear();
            }
            isLodmore = true;
            listCar.addAll(datas);
            if (adapter == null) {
                adapter = new DemandCarAdapter(DemandCarActivity.this, R.layout.layout_item_demand_car, listCar);
                recyclerView.setAdapter(adapter);
                adapter.setOnItemClickListener(this);
            } else {
                adapter.refresh(listCar);
            }
        } else {
            isLodmore = false;
            springView.setEnable(false);
        }
        springView.onFinishFreshAndLoad();
    }

    @OnClick({R.id.iv_return, R.id.tv_filter, R.id.btn_determine, R.id.btn_cancel, R.id.tv_car_name_title, R.id.tv_search})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_return:
                finish();
                break;
            case R.id.tv_filter://筛选
                FilterCarPop filterCarPop = new FilterCarPop(DemandCarActivity.this, this);
                filterCarPop.showAsDropDown(titleview);
                break;
            case R.id.btn_determine:
                if (carId > 0) {
                    dispatchId = CustomSharedPreferences.getString(DemandCarActivity.this, KeyBean.ORDER_ID.valueOf(), KeyBean.FILE_NAME.valueOf());
                    Logger.d("dispatchId====" + dispatchId);
                    Logger.d("carId====" + carId);
                    presenter.addDemandCar(DemandCarActivity.this, dispatchId, carId + "");
                } else {
                    showToast("请选择相似车源进行添加");
                }
                break;
            case R.id.tv_car_name_title:
                condPop.showAsDropDown(titleview, 25, 10);
                break;
            case R.id.btn_cancel:
                listCar.get(selectPosition).setCheck(false);
                adapter.notifyDataSetChanged();
                break;
            case R.id.tv_search:
                findCarBean.setType(fType);
                findCarBean.setKeyword(searchNameEdit.getText().toString());
                findCarBean.setPage(1);
                presenter.getDemandCars(findCarBean);
                break;
        }
    }

    @Override
    public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {
        carId = Integer.valueOf(listCar.get(position).getId());
        selectPosition = position;
        for (int i = 0; i < listCar.size(); i++) {
            if (i == position) {
                listCar.get(i).setCheck(true);
            } else {
                listCar.get(i).setCheck(false);
            }
        }
        adapter.notifyDataSetChanged();
    }

    @Override
    public boolean onItemLongClick(View view, RecyclerView.ViewHolder holder, int position) {
        return false;
    }

    private View.OnClickListener popListener = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            page = 1;
            switch (view.getId()) {
                case R.id.tv_car_name:
                    nameTitleTv.setText("车名");
                    searchNameEdit.setHint("请输入品牌/车系");
                    fType = 1;
                    break;
                case R.id.tv_car_main:
                    nameTitleTv.setText("车行名");
                    searchNameEdit.setHint("请输入车行名称");
                    fType = 2;
                    break;
                case R.id.tv_car_vin:
                    nameTitleTv.setText("VIN");
                    searchNameEdit.setHint("请输入VIN码");
                    fType = 3;
                    break;
                case R.id.tv_car_id:
                    nameTitleTv.setText("ID");
                    searchNameEdit.setHint("请输入ID码");
                    fType = 4;
                    break;
            }
            if (condPop.isShowing()) {
                condPop.dismiss();
            }
        }
    };

    @Override
    public void inquireCar(FindCarBean carBean) {
        page = 1;
        carBean.setBrand_id(brandId);
        findCarBean = carBean;
        presenter.getDemandCars(carBean);
    }

    @Override
    public void selectedBrand() {
        Intent intent = new Intent(DemandCarActivity.this, SelectCarBrandActivity.class);
        intent.putExtra("Brand", 3);
        startIntent(intent, 0);
    }

    @Override
    public void onRefresh() {
        refresh();
    }

    @Override
    public void onLoadmore() {
        refresh();
    }

    private void refresh() {
        if (isLodmore) {
            page++;
        }
        if (findCarBean == null) {
            findCarBean = new FindCarBean();
        }
        findCarBean.setPage(page);
        if (dateType == 1) {
            presenter.getDemandCars(findCarBean);
        } else {
            likePresenter.getLikeCars(findCarBean);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (resultCode) {
            case RequestAndResultCode.CarModelActivity_Result:
                brandId = data.getStringExtra("brandId");
                brandName = data.getStringExtra("brandName");
                RxBus.getInstance().sendData(data.getStringExtra("brandName"), null);
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }
}
